import axios from 'axios'

// 创建axios实例
const weatherApi = axios.create({
  baseURL: 'http://localhost:3000/api/weather',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加请求拦截器
weatherApi.interceptors.request.use(
  config => {
    console.log('发送请求:', {
      url: config.url,
      method: config.method,
      params: config.params,
      baseURL: config.baseURL
    })
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
weatherApi.interceptors.response.use(
  response => {
    console.log('收到响应:', response.data)
    return response
  },
  error => {
    console.error('API请求错误:', {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
      config: error.config
    })
    throw error
  }
)

// 获取城市天气数据
export const getWeatherByCity = async (city) => {
  try {
    console.log('正在请求城市天气:', city)
    const response = await weatherApi.get('/current', {
      params: { region: city }
    })
    console.log('获取到的天气数据:', response.data)
    return response.data
  } catch (error) {
    console.error('获取天气数据失败:', error)
    throw {
      code: error.response?.status || 500,
      message: error.response?.data?.message || '获取天气数据失败',
      error: error.message
    }
  }
}

// 获取生活指数数据
export const getLifeIndex = async (city) => {
  try {
    console.log('正在请求生活指数:', city)
    const response = await weatherApi.get('/lifeindex', {
      params: { region: city }
    })
    console.log('获取到的生活指数数据:', response.data)
    if (response.data.code === 200) {
      return response.data
    } else {
      throw new Error(response.data.message || '获取生活指数数据失败')
    }
  } catch (error) {
    console.error('获取生活指数数据失败:', error)
    throw {
      code: error.response?.status || 500,
      message: error.response?.data?.message || '获取生活指数数据失败',
      error: error.message
    }
  }
}

// 获取城市天气预报数据
export const getWeatherForecast = async (city) => {
  try {
    console.log('正在请求天气预报:', city)
    const response = await weatherApi.get('/forecast', {
      params: { region: city }
    })
    console.log('获取到的天气预报数据:', response.data)
    return response.data
  } catch (error) {
    console.error('获取天气预报数据失败:', error)
    throw {
      code: error.response?.status || 500,
      message: error.response?.data?.message || '获取天气预报数据失败',
      error: error.message
    }
  }
} 